<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/avatar.jpg">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/avatar.jpg">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/avatar.jpg">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-big-counter.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"raphets.github.io","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="Python文件读写相关代码介绍。">
<meta property="og:type" content="article">
<meta property="og:title" content="Python文件读写详解">
<meta property="og:url" content="https://raphets.github.io/archives/9ceffb4a.html">
<meta property="og:site_name" content="尚拙">
<meta property="og:description" content="Python文件读写相关代码介绍。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2024-01-30T05:58:45.000Z">
<meta property="article:modified_time" content="2024-01-30T06:05:05.743Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="文件读写">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://raphets.github.io/archives/9ceffb4a.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Python文件读写详解 | 尚拙</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">尚拙</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">一个分享技术、学习成长的个人博客网站</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-tool">

    <a href="/tool/" rel="section"><i class="fa fa-hammer fa-fw"></i>工具</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://raphets.github.io/archives/9ceffb4a.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="John Doe">
      <meta itemprop="description" content="不积跬步，无以至千里；不积小流，无以成江海。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="尚拙">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Python文件读写详解
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2024-01-30 13:58:45 / 修改时间：14:05:05" itemprop="dateCreated datePublished" datetime="2024-01-30T13:58:45+08:00">2024-01-30</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%8A%80%E6%9C%AF%E6%96%87%E7%AB%A0/" itemprop="url" rel="index"><span itemprop="name">技术文章</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%8A%80%E6%9C%AF%E6%96%87%E7%AB%A0/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>Python文件读写相关代码介绍。</p>
<span id="more"></span>

<h3 id="读写"><a href="#读写" class="headerlink" title="读写"></a>读写</h3><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"># 读操作</span><br><span class="line">with open(&#x27;file&#x27;, &#x27;r&#x27;, encoding=&#x27;utf-8&#x27;) as f:</span><br><span class="line">    print(f.read())</span><br><span class="line"></span><br><span class="line"># 写操作</span><br><span class="line">with open(&#x27;file&#x27;, &#x27;w&#x27;, encoding=&#x27;utf-8&#x27;) as f:</span><br><span class="line">    print(f.write(&#x27;你好&#x27;))</span><br></pre></td></tr></table></figure>


<p>#操作符</p>
<h3 id="一、python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法"><a href="#一、python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法" class="headerlink" title="一、python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法"></a>一、python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法</h3><p>1.得到当前工作目录，即当前Python脚本工作的目录路径: os.getcwd()</p>
<p>2.返回指定目录下的所有文件和目录名:os.listdir()</p>
<p>3.函数用来删除一个文件:os.remove()</p>
<p>4.删除多个目录：os.removedirs（r“c：\python”）</p>
<p>5.检验给出的路径是否是一个文件：os.path.isfile()</p>
<p>6.检验给出的路径是否是一个目录：os.path.isdir()</p>
<p>7.判断是否是绝对路径：os.path.isabs()</p>
<p>8.检验给出的路径是否真地存:os.path.exists()</p>
<p>9.返回一个路径的目录名和文件名:os.path.split() eg os.path.split(‘&#x2F;home&#x2F;swaroop&#x2F;byte&#x2F;code&#x2F;poem.txt’) 结果：(‘&#x2F;home&#x2F;swaroop&#x2F;byte&#x2F;code’, ‘poem.txt’) </p>
<p>10.分离扩展名：os.path.splitext()</p>
<p>11.获取路径名：os.path.dirname()</p>
<p>12.获取文件名：os.path.basename()</p>
<p>13.运行shell命令: os.system()</p>
<p>14.读取和设置环境变量:os.getenv() 与os.putenv()</p>
<p>15.给出当前平台使用的行终止符:os.linesep Windows使用’\r\n’，Linux使用’\n’而Mac使用’\r’</p>
<p>16.指示你正在使用的平台：os.name 对于Windows，它是’nt’，而对于Linux&#x2F;Unix用户，它是’posix’</p>
<p>17.重命名：os.rename（old， new）</p>
<p>18.创建多级目录：os.makedirs（r“c：\python\test”）</p>
<p>19.创建单个目录：os.mkdir（“test”）</p>
<p>20.获取文件属性：os.stat（file）</p>
<p>21.修改文件权限与时间戳：os.chmod（file）</p>
<p>22.终止当前进程：os.exit（）</p>
<p>23.获取文件大小：os.path.getsize（filename）</p>
<h3 id="二、文件操作方法大全："><a href="#二、文件操作方法大全：" class="headerlink" title="二、文件操作方法大全："></a>二、文件操作方法大全：</h3><p>1.os.mknod(“test.txt”) #创建空文件</p>
<p>2.fp &#x3D; open(“test.txt”,w) #直接打开一个文件，如果文件不存在则创建文件</p>
<p>3.关于open 模式：</p>
<pre><code>复制代码 代码如下:
w：以写方式打开，
a：以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+：以读写模式打开
w+：以读写模式打开 (参见 w )
a+：以读写模式打开 (参见 a )
rb：以二进制读模式打开
wb：以二进制写模式打开 (参见 w )
ab：以二进制追加模式打开 (参见 a )
rb+：以二进制读写模式打开 (参见 r+ )
wb+：以二进制读写模式打开 (参见 w+ )
ab+：以二进制读写模式打开 (参见 a+ )

fp.read([size]) #size为读取的长度，以byte为单位

fp.readline([size]) #读一行，如果定义了size，有可能返回的只是一行的一部分

fp.readlines([size]) #把文件每一行作为一个list的一个成员，并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数，size是表示读取内容的总长，也就是说可能只读到文件的一部分。

fp.write(str) #把str写到文件中，write()并不会在str后加上一个换行符

fp.writelines(seq) #把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入，不会在每行后面加上任何东西。

fp.close() #关闭文件。python会在一个文件不用后自动关闭文件，不过这一功能没有保证，最好还是养成自己关闭的习惯。 如果一个文件在关闭后还对其进行操作会产生ValueError

fp.flush() #把缓冲区的内容写入硬盘

fp.fileno() #返回一个长整型的”文件标签“

fp.isatty() #文件是否是一个终端设备文件（unix系统中的）

fp.tell() #返回文件操作标记的当前位置，以文件的开头为原点

fp.next() #返回下一行，并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时，就是调用next()函数来实现遍历的。

fp.seek(offset[,whence]) #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的，一般为正数。但如果提供了whence参数就不一定了，whence可以为0表示从头开始计算，1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意，如果文件以a或a+的模式打开，每次进行写操作时，文件操作标记会自动返回到文件末尾。

fp.truncate([size]) #把文件裁成规定的大小，默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大，依据系统的不同可能是不改变文件，也可能是用0把文件补到相应的大小，也可能是以一些随机的内容加上去。
</code></pre>
<h3 id="三、目录操作方法大全"><a href="#三、目录操作方法大全" class="headerlink" title="三、目录操作方法大全"></a>三、目录操作方法大全</h3><p>1.创建目录</p>
 <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">os.mkdir(&quot;file&quot;) </span><br></pre></td></tr></table></figure>

<p>2.复制文件：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">shutil.copyfile(&quot;oldfile&quot;,&quot;newfile&quot;) #oldfile和newfile都只能是文件</span><br><span class="line">shutil.copy(&quot;oldfile&quot;,&quot;newfile&quot;) #oldfile只能是文件夹，newfile可以是文件，也可以是目标目录</span><br></pre></td></tr></table></figure>
<p>3.复制文件夹：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">shutil.copytree(&quot;olddir&quot;,&quot;newdir&quot;) #olddir和newdir都只能是目录，且newdir必须不存在</span><br></pre></td></tr></table></figure>

<p>4.重命名文件（目录）</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">os.rename(&quot;oldname&quot;,&quot;newname&quot;) #文件或目录都是使用这条命令</span><br></pre></td></tr></table></figure>

<p>5.移动文件（目录）</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">shutil.move(&quot;oldpos&quot;,&quot;newpos&quot;) </span><br></pre></td></tr></table></figure>

<p>6.删除文件</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">os.remove(&quot;file&quot;)</span><br></pre></td></tr></table></figure>

<p>7.删除目录</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">os.rmdir(&quot;dir&quot;) #只能删除空目录</span><br><span class="line">shutil.rmtree(&quot;dir&quot;) #空目录、有内容的目录都可以删</span><br></pre></td></tr></table></figure>

<p>8.转换目录</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">os.chdir(&quot;path&quot;) #换路径</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E6%96%87%E4%BB%B6%E8%AF%BB%E5%86%99/" rel="tag"><i class="fa fa-tag"></i> 文件读写</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/archives/5dcc0b15.html" rel="prev" title="PBL教学法">
      <i class="fa fa-chevron-left"></i> PBL教学法
    </a></div>
      <div class="post-nav-item">
    <a href="/archives/5f48daf9.html" rel="next" title="Python连接MySql并插入数据操作详解">
      Python连接MySql并插入数据操作详解 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AF%BB%E5%86%99"><span class="nav-number">1.</span> <span class="nav-text">读写</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%80%E3%80%81python%E4%B8%AD%E5%AF%B9%E6%96%87%E4%BB%B6%E3%80%81%E6%96%87%E4%BB%B6%E5%A4%B9%E6%93%8D%E4%BD%9C%E6%97%B6%E7%BB%8F%E5%B8%B8%E7%94%A8%E5%88%B0%E7%9A%84os%E6%A8%A1%E5%9D%97%E5%92%8Cshutil%E6%A8%A1%E5%9D%97%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="nav-number">2.</span> <span class="nav-text">一、python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C%E6%96%B9%E6%B3%95%E5%A4%A7%E5%85%A8%EF%BC%9A"><span class="nav-number">3.</span> <span class="nav-text">二、文件操作方法大全：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E7%9B%AE%E5%BD%95%E6%93%8D%E4%BD%9C%E6%96%B9%E6%B3%95%E5%A4%A7%E5%85%A8"><span class="nav-number">4.</span> <span class="nav-text">三、目录操作方法大全</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="John Doe"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">John Doe</p>
  <div class="site-description" itemprop="description">不积跬步，无以至千里；不积小流，无以成江海。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">47</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">John Doe</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
